package ar.com.sectorwine.controllers;

import java.security.Principal;
import java.util.Locale;
import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.Valid;
import javax.validation.Validator;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.ModelAndView;

import ar.com.sectorwine.dto.EmpresaDTO;
import ar.com.sectorwine.dto.EmpresasDTOMapper;
import ar.com.sectorwine.entities.Empresa;
import ar.com.sectorwine.entities.Users;
import ar.com.sectorwine.services.EmpresasService;
import ar.com.sectorwine.services.UsuarioService;

/**
 * Handles requests for the application home page.
 */
@Controller
@Transactional(propagation = Propagation.REQUIRES_NEW)
public class EmpresasController {

	@Autowired
	private EmpresasService empresasService;
	@Autowired
	private UsuarioService usuarioService;
	@Autowired
	private EmpresasDTOMapper empresasDTOMapper;

	private static final Logger logger = LoggerFactory
			.getLogger(EmpresasController.class);
	@Autowired
	private Validator validator;

	/**
	 * Simply selects the home view to render by returning its name.
	 */
	@RequestMapping(value = "empresas_alta", method = RequestMethod.GET)
	public String registro(Locale locale, Model model) {

		logger.info("Welcome home! the client locale is " + locale.toString());
		model.addAttribute("empresa", new EmpresaDTO());
		return "empresas/empresas_alta";
	}

	@RequestMapping(value = "/empresas_alta", method = RequestMethod.POST)
	public ModelAndView create(
			@Valid @ModelAttribute("empresa") EmpresaDTO empresaDTO,
			BindingResult result, SessionStatus status, Principal principal) {
		logger.info("controller");
		Empresa empresa = empresasDTOMapper
				.obtenerObjetoDelDominioDesdeDTO(empresaDTO);

		Users usuarioActual = usuarioService.getUsuario(principal.getName());

		Set<ConstraintViolation<EmpresaDTO>> failures = validator
				.validate(empresaDTO);

		if (failures.size() == 0) {
			if (empresa != null) {
				empresasService.crearEmpresa(empresa, usuarioActual);
				status.setComplete();
				ModelAndView mav = new ModelAndView("home");
				mav.addObject("empresa", empresaDTO);
				return mav;
			} else {
				ModelAndView mav = new ModelAndView("empresas/empresas_alta");
				mav.addObject("empresa", empresaDTO);
				return mav;
			}
		} else {
			ModelAndView mav = new ModelAndView("empresas/empresas_alta");
			mav.addObject("empresa", empresaDTO);
			for (Object o : failures) {
				logger.info(o.toString());
			}
			return mav;
		}

	}

	/**
	 * Simply selects the home view to render by returning its name.
	 */
	@RequestMapping(value = "empresas_miempresa", method = RequestMethod.GET)
	public ModelAndView miEmpresa(Locale locale, Model model,
			Principal principal) {

		Users usuarioActual = usuarioService.getUsuario(principal.getName());
		ModelAndView mav = new ModelAndView("empresas/empresas_miempresa");

		mav.addObject("mi_empresa", usuarioActual.getPerfilUsuario()
				.getEmpresa());
		return mav;
	}

	/**
	 * Simply selects the home view to render by returning its name.
	 */
	@RequestMapping(value = "empresas_modificar", method = RequestMethod.GET)
	public ModelAndView modificar(Locale locale, @RequestParam String id,
			Model model) {

		logger.info("Welcome home! the client locale is " + locale.toString());

		ModelAndView mav = new ModelAndView("empresas/empresas_modificar");

		Empresa empresa_buscada = empresasService.getEmpresa(id);
		mav.addObject("empresa", empresa_buscada);
		return mav;
	}

	@RequestMapping(value = "empresas_modificar", method = RequestMethod.POST)
	public ModelAndView modificar(
			@Valid @ModelAttribute("empresa") EmpresaDTO empresaDTO,
			BindingResult result, SessionStatus status) {

		logger.info("controller");
		Empresa empresa = empresasDTOMapper
				.obtenerObjetoDelDominioDesdeDTO(empresaDTO);

		Set<ConstraintViolation<EmpresaDTO>> failures = validator
				.validate(empresaDTO);

		if (failures.size() == 0) {
			if (empresa != null) {
				empresasService.modificarEmpresa(empresa);
				status.setComplete();
				ModelAndView mav = new ModelAndView("home");
				mav.addObject("empresa", empresaDTO);
				return mav;
			} else {
				ModelAndView mav = new ModelAndView(
						"empresas/empresas_modificar");
				mav.addObject("empresa", empresaDTO);
				return mav;
			}
		} else {
			ModelAndView mav = new ModelAndView("empresas/empresas_modificar");
			mav.addObject("empresa", empresaDTO);
			for (Object o : failures) {
				logger.info(o.toString());
			}
			return mav;
		}

	}

	@RequestMapping(value = "empresa_baja", method = RequestMethod.POST)
	public ModelAndView darBajaLogica(Locale locale, @RequestParam String id,
			Model model) {

		logger.info("controller");

		ModelAndView mav = new ModelAndView("home");
		mav.addObject("resultado", empresasService.bajaEmpresa(id));
		return mav;
	}

	/**
	 * Simply selects the home view to render by returning its name.
	 */
	@RequestMapping(value = "empresas_listar", method = RequestMethod.GET)
	public ModelAndView listar(Locale locale, Model model) {
		ModelAndView mav = new ModelAndView("empresas/empresas_listar");
		mav.addObject("usuariosList", usuarioService.getListaUsuarios());
		return mav;
	}

	@RequestMapping(value = "empresas_perfil", method = RequestMethod.GET)
	public ModelAndView verPerfil(Locale locale, Model model,
			@RequestParam String id) {
		ModelAndView mav = new ModelAndView("empresas/empresas_perfil");
		mav.addObject("empresa", empresasService.getEmpresa(id));
		return mav;
	}
}